<template>
  <div class="person-management">
    <!-- 搜索筛选区域 -->
    <div class="search-filters">
      <div class="filter-row">
        <!-- 姓名搜索 -->
        <div>
          <span class="search-item">姓名</span>
          <input
              v-model="searchForm.name"
              type="text"
              placeholder="请输入姓名"
              class="input-field"
          />
        </div>

        <!-- 联系电话搜索 -->
        <div>
          <span class="search-item">联系电话</span>
          <input
              v-model="searchForm.phone"
              type="text"
              placeholder="请输入联系电话"
              class="input-field"
          />
        </div>

        <!-- 身份搜索 -->
        <div>
          <span class="search-item">身份</span>
          <select v-model="searchForm.identity" class="select-field">
            <option value="">全部</option>
            <option value="租户">租户</option>
            <option value="成员">成员</option>
          </select>
        </div>

        <button @click="handleSearch" class="btn-primary">
          <img src="https://lanhu-oss-proxy.lanhuapp.com/SketchPnga03cd43e27317f20428660e14317e35a64a3d907d88f824770f063b2f9fd5f10" alt="搜索" class="btn-icon" />
          搜索
        </button>
        <button @click="handleReset" class="btn-secondary">
          <img src="https://lanhu-oss-proxy.lanhuapp.com/SketchPngd1ee69767e02bb56b7c745624d059b292108792e966600668227ff5d22467bbe" alt="重置" class="btn-icon" />
          重置
        </button>
      </div>
    </div>

    <!-- 分割线 -->
    <div class="divider"></div>

    <!-- 操作按钮组 -->
    <div class="operation-buttons">
      <button
          @click="handleAdd"
          :class="['btn-add', { 'btn-selected': operationMode === 'add' }]"
      >
        <img src="https://lanhu-oss-proxy.lanhuapp.com/SketchPngf1cdfd3741aaeaf19e733deebf065b44a820a4e6e4d83792de3c6e699c670645" alt="新增" class="btn-icon" />
        新增
      </button>

      <button
          @click="handleModeChange('edit')"
          :class="['btn-add', { 'btn-selected': operationMode === 'edit' }]"
      >
        <img src="https://lanhu-oss-proxy.lanhuapp.com/SketchPng8dd30a7302a6f2ab4df9f28606f440873a476132867bc3718014adf8e7a187da" alt="修改" class="btn-icon" />
        修改
      </button>

      <button
          @click="handleModeChange('delete')"
          :class="['btn-add', { 'btn-selected': operationMode === 'delete' }]"
      >
        <img src="https://lanhu-oss-proxy.lanhuapp.com/SketchPng7e588fa8b8650f5efd6ef1233ed984dd6881ff2d70f829a9cd26b4482d233394" alt="删除" class="btn-icon" />
        删除
      </button>

      <!-- 导出按钮 -->
      <button @click="handleExport" class="btn-add">
        <img src="https://lanhu-oss-proxy.lanhuapp.com/SketchPng7e588fa8b8650f5efd6ef1233ed984dd6881ff2d70f829a9cd26b4482d233394" alt="导出" class="btn-icon" />
        导出
      </button>

      <!-- 显示模式切换按钮 -->
      <button @click="toggleDisplayMode" class="btn-add">
        {{ displayMode === 'tenantOnly' ? '显示所有人员' : '仅显示户主' }}
      </button>

      <!-- 批量删除按钮 -->
      <button
          v-if="operationMode === 'delete' && selectedRecords.length > 0"
          @click="handleBatchDelete"
          class="btn-batch-delete"
      >
        批量删除 ({{ selectedRecords.length }})
      </button>
    </div>

    <!-- 数据表格 -->
    <div class="table-container">
      <table class="data-table">
        <thead>
        <tr class="table-header">
          <!-- 删除模式下显示全选框 -->
          <th v-if="operationMode === 'delete'">
            <input
                type="checkbox"
                @change="handleSelectAll"
                :checked="isAllSelected"
                class="checkbox"
            />
          </th>
          <th>序号</th>
          <th>姓名</th>
          <th>性别</th>
          <th>联系电话</th>
          <th>身份</th>
          <th>身份证号</th>
          <th>与户主关系</th>
          <th>紧急联系人</th>
          <th>紧急联系人电话</th>
          <th>操作</th>
        </tr>
        </thead>
        <tbody>
        <template v-for="(item, index) in paginatedData" :key="item.type + '-' + (item.data.tenementId || item.data.memberId)">
          <!-- 户主信息行 -->
          <tr v-if="item.type === 'tenant'" class="table-row" :class="{ 'member-row': false }">
            <!-- 删除模式下显示复选框 -->
            <td v-if="operationMode === 'delete'">
              <input
                  type="checkbox"
                  :value="item.data.tenementId"
                  v-model="selectedRecords"
                  class="checkbox"
              />
            </td>
            <td>{{ item.index }}</td>
            <td>{{ item.data.name }}</td>
            <td>{{ item.data.gender === 1 ? '男' : '女' }}</td>
            <td>{{ item.data.phone }}</td>
            <td>户主</td>
            <td>{{ item.data.idCard }}</td>
            <td>-</td>
            <td>-</td>
            <td>-</td>
            <td class="action-buttons">
              <!-- 查看按钮 - 始终显示 -->
              <button @click="handleView(item.data, 'tenant')" class="action-btn" title="查看详情">
                <img src="https://lanhu-oss-proxy.lanhuapp.com/SketchPng7e588fa8b8650f5efd6ef1233ed984dd6881ff2d70f829a9cd26b4482d233394" alt="查看" />
              </button>

              <!-- 编辑按钮 - 修改模式下显示 -->
              <button v-if="operationMode === 'edit'" @click="handleEdit(item.data, 'tenant')" class="action-btn" title="编辑">
                <img src="https://lanhu-oss-proxy.lanhuapp.com/SketchPng8dd30a7302a6f2ab4df9f28606f440873a476132867bc3718014adf8e7a187da" alt="编辑" />
              </button>

              <!-- 删除按钮 - 删除模式下显示 -->
              <button v-if="operationMode === 'delete'" @click="handleSingleDelete(item.data, 'tenant')" class="action-btn" title="删除">
                <img src="https://lanhu-oss-proxy.lanhuapp.com/SketchPng7e588fa8b8650f5efd6ef1233ed984dd6881ff2d70f829a9cd26b4482d233394" alt="删除" />
              </button>

              <!-- 为户主添加新增成员按钮 -->
              <button
                v-if="operationMode === 'add-member' || showAddMemberButton"
                @click="handleAddMember(item.data)"
                class="action-btn"
                title="新增成员">
                <img src="https://lanhu-oss-proxy.lanhuapp.com/SketchPngf1cdfd3741aaeaf19e733deebf065b44a820a4e6e4d83792de3c6e699c670645" alt="新增成员" />
              </button>
            </td>
          </tr>

          <!-- 成员信息行 -->
          <tr v-else-if="item.type === 'member'" class="table-row member-row">
            <td v-if="operationMode === 'delete'">
              <input
                  type="checkbox"
                  :value="item.data.memberId"
                  v-model="selectedRecords"
                  class="checkbox"
              />
            </td>
            <td>{{ item.index }}</td>
            <td>{{ item.data.memberName }}</td>
            <td>{{ item.data.gender === 1 ? '男' : '女' }}</td>
            <td>{{ item.data.memberPhone }}</td>
            <td>成员</td>
            <td>{{ item.data.idCard }}</td>
            <td>{{ item.data.relationship }}</td>
            <td>-</td>
            <td>-</td>
            <td class="action-buttons">
              <!-- 查看按钮 - 始终显示 -->
              <button @click="handleView(item.data, 'member')" class="action-btn" title="查看详情">
                <img src="https://lanhu-oss-proxy.lanhuapp.com/SketchPng7e588fa8b8650f5efd6ef1233ed984dd6881ff2d70f829a9cd26b4482d233394" alt="查看" />
              </button>

              <!-- 编辑按钮 - 修改模式下显示 -->
              <button v-if="operationMode === 'edit'" @click="handleEdit(item.data, 'member')" class="action-btn" title="编辑">
                <img src="https://lanhu-oss-proxy.lanhuapp.com/SketchPng8dd30a7302a6f2ab4df9f28606f440873a476132867bc3718014adf8e7a187da" alt="编辑" />
              </button>

              <!-- 删除按钮 - 删除模式下显示 -->
              <button v-if="operationMode === 'delete'" @click="handleSingleDelete(item.data, 'member')" class="action-btn" title="删除">
                <img src="https://lanhu-oss-proxy.lanhuapp.com/SketchPng7e588fa8b8650f5efd6ef1233ed984dd6881ff2d70f829a9cd26b4482d233394" alt="删除" />
              </button>
            </td>
          </tr>
        </template>
        </tbody>
      </table>
    </div>

    <!-- 分页组件 -->
    <div class="pagination">
      <span class="pagination-info">共 {{ pagination.totalPages }} 页，{{ pagination.total }} 条记录</span>
      <button @click="goToPrevPage" :disabled="pagination.currentPage === 1" class="pagination-btn">上一页</button>
      <button
          v-for="page in visiblePages"
          :key="page"
          @click="goToPage(page)"
          :class="['pagination-btn', { 'active': page === pagination.currentPage }]"
      >
        {{ page }}
      </button>
      <button @click="goToNextPage" :disabled="pagination.currentPage === pagination.totalPages" class="pagination-btn">下一页</button>
      <span class="pagination-goto">前往</span>
      <input v-model.number="gotoPage" @keyup.enter="handleGotoPage" class="goto-input" />
      <span>页</span>
    </div>

    <!-- 新增类型选择弹窗 -->
    <div v-if="showAddTypeModal" class="modal-overlay" @click="closeAddTypeModal">
      <div class="modal-content add-type-modal" @click.stop>
        <div class="modal-header">
          <h3>选择新增类型</h3>
          <button @click="closeAddTypeModal" class="close-btn">×</button>
        </div>
        <div class="modal-body add-type-options">
          <button @click="openAddTenantModal" class="add-type-btn">
            新增户主信息
          </button>
          <button @click="enterAddMemberMode" class="add-type-btn">
            新增成员信息
          </button>
        </div>
      </div>
    </div>

    <!-- 新增/编辑/查看弹窗 -->
    <div v-if="showModal" class="modal-overlay" @click="closeModal">
      <div class="modal-content" @click.stop>
        <div class="modal-header">
          <h3>{{ modalTitle }}</h3>
          <button @click="closeModal" class="close-btn">×</button>
        </div>
        <div class="modal-body">
          <div class="form-grid">
            <div class="form-item">
              <label>姓名</label>
              <input v-model="currentRecord.name" :disabled="modalType === 'view'" class="form-input" />
            </div>
            <div class="form-item">
              <label>性别</label>
              <select v-model="currentRecord.gender" :disabled="modalType === 'view'" class="form-input">
                <option value="1">男</option>
                <option value="0">女</option>
              </select>
            </div>
            <div class="form-item">
              <label>联系电话</label>
              <input v-model="currentRecord.phone" :disabled="modalType === 'view'" class="form-input" />
            </div>
            <div class="form-item">
              <label>身份</label>
              <select v-model="currentRecord.identity" :disabled="modalType === 'view'" class="form-input" @change="handleIdentityChange">
                <option value="租户">户主</option>
                <option value="成员">成员</option>
              </select>
            </div>
            <div v-if="currentRecord.identity === '成员' && modalType === 'add'" class="form-item">
              <label>关联户主</label>
              <select v-model="currentRecord.tenantId" class="form-input">
                <option v-for="tenant in tenantList" :key="tenant.tenementId" :value="tenant.tenementId">
                  {{ tenant.name }}
                </option>
              </select>
            </div>
            <div class="form-item">
              <label>身份证号</label>
              <input v-model="currentRecord.idCard" :disabled="modalType === 'view'" class="form-input" />
            </div>
            <div class="form-item">
              <label>与户主关系</label>
              <input v-model="currentRecord.relationshipWithTenant" :disabled="modalType === 'view' || currentRecord.identity === '租户'" class="form-input" />
            </div>

            <div class="form-item">
              <label>备注</label>
              <textarea v-model="currentRecord.remark" :disabled="modalType === 'view'" class="form-textarea"></textarea>
            </div>
          </div>

          <!-- 系统信息（仅查看模式显示） -->
          <div v-if="modalType === 'view'" class="system-info">
            <h4>系统信息</h4>
            <div class="detail-grid">
              <div class="detail-item">
                <label>创建人：</label>
                <span>{{ currentRecord.creator }}</span>
              </div>
              <div class="detail-item">
                <label>更新人：</label>
                <span>{{ currentRecord.updater }}</span>
              </div>
              <div class="detail-item">
                <label>创建时间：</label>
                <span>{{ currentRecord.createTime }}</span>
              </div>
              <div class="detail-item">
                <label>更新时间：</label>
                <span>{{ currentRecord.updateTime }}</span>
              </div>
              <div v-if="currentRecord.identity === '成员'" class="detail-item">
                <label>关联户主：</label>
                <span>{{ getTenantNameById(currentRecord.tenantId) }}</span>
              </div>
            </div>
          </div>
        </div>
        <div v-if="modalType !== 'view'" class="modal-footer">
          <button @click="closeModal" class="btn-cancel">取消</button>
          <button @click="handleSave" class="btn-save">保存</button>
        </div>
        <div v-else class="modal-footer">
          <button @click="closeModal" class="btn-cancel">关闭</button>
        </div>
      </div>
    </div>

    <!-- 删除确认弹窗 -->
    <div v-if="showDeleteConfirm" class="modal-overlay" @click="cancelDelete">
      <div class="modal-content delete-confirm-modal" @click.stop>
        <div class="modal-header">
          <h3>确认删除</h3>
          <button @click="cancelDelete" class="close-btn">×</button>
        </div>
        <div class="modal-body">
          <p v-if="deleteType === 'single'">确定要删除人员 "{{ deleteTarget.name }}" 吗？</p>
          <p v-else>确定要删除选中的 {{ selectedRecords.length }} 个人员吗？</p>
        </div>
        <div class="modal-footer">
          <button @click="cancelDelete" class="btn-cancel">取消</button>
          <button @click="confirmDelete" class="btn-delete">删除</button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import {getMemberInfo, getTenantInfo} from "@/api/person.js"

// 响应式数据
const searchForm = ref({
  name: '',
  phone: '',
  identity: ''
})

// 获取人员信息
const tenantRecords = ref([])  // 户主数据
const memberRecords = ref([])  // 成员数据
const loading = ref(false)
const displayMode = ref('tenantOnly') // 'tenantOnly' | 'allWithHierarchy'

const fetchRecords = async () => {
  loading.value = true
  try {
    // 首先获取户主信息
    const tenantResponse = await getTenantInfo()
    tenantRecords.value = (tenantResponse.data || []).map(item => ({
      ...item,
      phone: item.phoneNumber,
      identity: '租户'
    }))

    // 获取成员信息
    const memberResponse = await getMemberInfo()
    memberRecords.value = (memberResponse.data || []).map(item => ({
      ...item,
      identity: '成员'
    }))

    // 初始化显示
    updatePagination()
  } catch (error) {
    console.error("获取人员数据失败", error)
  } finally {
    loading.value = false
  }
}

// 切换显示模式
const toggleDisplayMode = () => {
  displayMode.value = displayMode.value === 'tenantOnly' ? 'allWithHierarchy' : 'tenantOnly'
  pagination.value.currentPage = 1
  selectedRecords.value = []
  updatePagination()
}

const pagination = ref({
  currentPage: 1,
  pageSize: 10,
  totalPages: 1,
  total: 0
})

const showModal = ref(false)
const showAddTypeModal = ref(false)
const modalType = ref('add') // 'add', 'edit', 'view'
const currentRecord = ref({})
const gotoPage = ref('')
const recordType = ref('') // 记录类型: 'tenant' 或 'member'

// 新增的状态变量
const operationMode = ref('') // '', 'edit', 'delete', 'add-member'
const selectedRecords = ref([])
const showDeleteConfirm = ref(false)
const deleteType = ref('single') // 'single', 'batch'
const deleteTarget = ref({})

// 控制新增成员按钮显示状态
const showAddMemberButton = ref(false)

// 计算属性 - 分页后的记录
const paginatedData = computed(() => {
  let flatList = []

  if (displayMode.value === 'tenantOnly') {
    // 仅显示户主
    flatList = tenantRecords.value.map((tenant, index) => ({
      type: 'tenant',
      data: tenant,
      index: index + 1
    }))
  } else {
    // 显示户主和成员的扁平化列表
    let currentIndex = 1
    tenantRecords.value.forEach(tenant => {
      flatList.push({
        type: 'tenant',
        data: tenant,
        index: currentIndex++
      })

      // 添加该户主的成员
      const members = getMembersByTenantId(tenant.tenementId)
      members.forEach((member, memberIndex) => {
        flatList.push({
          type: 'member',
          data: member,
          index: `${currentIndex - 1}.${memberIndex + 1}`
        })
      })
    })
  }

  // 实现分页
  const start = (pagination.value.currentPage - 1) * pagination.value.pageSize
  const end = start + pagination.value.pageSize
  return flatList.slice(start, end)
})

// 计算属性
const modalTitle = computed(() => {
  switch (modalType.value) {
    case 'add': return '新增人员信息'
    case 'edit': return '编辑人员信息'
    case 'view': return '查看人员信息详情'
    default: return ''
  }
})

const visiblePages = computed(() => {
  const current = pagination.value.currentPage
  const total = pagination.value.totalPages
  const pages = []

  for (let i = Math.max(1, current - 2); i <= Math.min(total, current + 2); i++) {
    pages.push(i)
  }

  return pages
})

const isAllSelected = computed(() => {
  if (paginatedData.value.length === 0) return false

  // 检查当前页的所有记录是否都被选中
  const allIdsOnPage = paginatedData.value.map(item =>
    item.type === 'tenant' ? item.data.tenementId : item.data.memberId
  )

  return allIdsOnPage.length > 0 && allIdsOnPage.every(id => selectedRecords.value.includes(id))
})

const handleSelectAll = (event) => {
  if (event.target.checked) {
    // 收集当前页所有记录的ID
    selectedRecords.value = paginatedData.value.map(item =>
      item.type === 'tenant' ? item.data.tenementId : item.data.memberId
    )
  } else {
    selectedRecords.value = []
  }
}

// 获取户主列表
const tenantList = computed(() => {
  return tenantRecords.value
})

// 方法
const updatePagination = () => {
  let totalRecords = 0

  if (displayMode.value === 'tenantOnly') {
    totalRecords = tenantRecords.value.length
  } else {
    // 计算户主和所有成员的总数
    totalRecords = tenantRecords.value.length
    memberRecords.value.forEach(member => {
      totalRecords++
    })
  }

  pagination.value.total = totalRecords
  pagination.value.totalPages = Math.ceil(totalRecords / pagination.value.pageSize)
  if (pagination.value.currentPage > pagination.value.totalPages) {
    pagination.value.currentPage = 1
  }

  // 重置选中记录
  selectedRecords.value = []
}

const handleSearch = () => {
  // 搜索功能需要重新实现，这里简化处理
  pagination.value.currentPage = 1
  selectedRecords.value = []
  updatePagination()
}

const handleReset = () => {
  searchForm.value = {
    name: '',
    phone: '',
    identity: ''
  }

  pagination.value.currentPage = 1
  selectedRecords.value = []
  updatePagination()
}

const handleAdd = () => {
  operationMode.value = ''
  selectedRecords.value = []
  showAddTypeModal.value = true
}

const openAddTenantModal = () => {
  closeAddTypeModal()
  modalType.value = 'add'
  recordType.value = 'tenant'
  currentRecord.value = {
    name: '',
    gender: '1',
    phone: '',
    identity: '租户',
    idCard: '',
    relationshipWithTenant: '',
    remark: '',
    creator: '当前用户',
    updater: '当前用户',
    createTime: new Date().toLocaleString(),
    updateTime: new Date().toLocaleString()
  }
  showModal.value = true
}

const enterAddMemberMode = () => {
  closeAddTypeModal()
  operationMode.value = 'add-member'
  showAddMemberButton.value = true
}

const handleAddMember = (tenant) => {
  modalType.value = 'add'
  recordType.value = 'member'
  currentRecord.value = {
    name: '',
    gender: '1',
    phone: '',
    identity: '成员',
    tenantId: tenant.tenementId,
    idCard: '',
    relationshipWithTenant: '',
    remark: '',
    creator: '当前用户',
    updater: '当前用户',
    createTime: new Date().toLocaleString(),
    updateTime: new Date().toLocaleString()
  }
  showModal.value = true
}

const closeAddTypeModal = () => {
  showAddTypeModal.value = false
}

const handleModeChange = (mode) => {
  operationMode.value = mode
  showAddMemberButton.value = false
  selectedRecords.value = []
}

const handleEdit = (record, type) => {
  modalType.value = 'edit'
  recordType.value = type

  if (type === 'tenant') {
    currentRecord.value = {
      ...record,
      id: record.tenementId,
      name: record.name,
      gender: record.gender,
      phone: record.phone,
      identity: '租户',
      idCard: record.idCard,
      relationshipWithTenant: '-',
      remark: record.remark,
      creator: record.createBy,
      updater: record.updateBy,
      createTime: record.createTime,
      updateTime: record.updateTime
    }
  } else {
    currentRecord.value = {
      ...record,
      id: record.memberId,
      name: record.memberName,
      gender: record.gender,
      phone: record.memberPhone,
      identity: '成员',
      idCard: record.idCard,
      relationshipWithTenant: record.relationship,
      remark: record.remark,
      creator: record.createBy,
      updater: record.updateBy,
      createTime: record.createTime,
      updateTime: record.updateTime,
      tenantId: record.tenementId
    }
  }

  showModal.value = true
}

const handleView = (record, type) => {
  modalType.value = 'view'
  recordType.value = type

  if (type === 'tenant') {
    currentRecord.value = {
      ...record,
      id: record.tenementId,
      name: record.name,
      gender: record.gender,
      phone: record.phone,
      identity: '租户',
      idCard: record.idCard,
      relationshipWithTenant: '-',
      remark: record.remark,
      creator: record.createBy,
      updater: record.updateBy,
      createTime: record.createTime,
      updateTime: record.updateTime
    }
  } else {
    currentRecord.value = {
      ...record,
      id: record.memberId,
      name: record.memberName,
      gender: record.gender,
      phone: record.memberPhone,
      identity: '成员',
      idCard: record.idCard,
      relationshipWithTenant: record.relationship,
      remark: record.remark,
      creator: record.createBy,
      updater: record.updateBy,
      createTime: record.createTime,
      updateTime: record.updateTime,
      tenantId: record.tenementId
    }
  }

  showModal.value = true
}

const handleSingleDelete = (record, type) => {
  deleteType.value = 'single'
  deleteTarget.value = {
    ...record,
    type: type,
    id: type === 'tenant' ? record.tenementId : record.memberId,
    name: type === 'tenant' ? record.name : record.memberName
  }
  showDeleteConfirm.value = true
}

const handleBatchDelete = () => {
  if (selectedRecords.value.length === 0) return
  deleteType.value = 'batch'
  showDeleteConfirm.value = true
}

const handleExport = () => {
  // 导出功能实现
  console.log('导出数据')
}

const handleIdentityChange = () => {
  // 当身份为户主时，清空与户主关系
  if (currentRecord.value.identity === '租户') {
    currentRecord.value.relationshipWithTenant = ''
  }
}

const confirmDelete = () => {
  if (deleteType.value === 'single') {
    // 单个删除
    const target = deleteTarget.value
    if (target.type === 'tenant') {
      tenantRecords.value = tenantRecords.value.filter(record => record.tenementId !== target.id)
      // 同时删除关联的成员
      memberRecords.value = memberRecords.value.filter(member => member.tenementId !== target.id)
    } else {
      memberRecords.value = memberRecords.value.filter(record => record.memberId !== target.id)
    }
  } else {
    // 批量删除
    const tenantIdsToDelete = selectedRecords.value.filter(id => {
      return tenantRecords.value.some(t => t.tenementId === id)
    })

    const memberIdsToDelete = selectedRecords.value.filter(id => {
      return memberRecords.value.some(m => m.memberId === id)
    })

    // 删除户主及其成员
    tenantRecords.value = tenantRecords.value.filter(record => {
      const shouldDelete = tenantIdsToDelete.includes(record.tenementId)
      if (shouldDelete) {
        // 同时删除关联的成员
        memberRecords.value = memberRecords.value.filter(member => member.tenementId !== record.tenementId)
      }
      return !shouldDelete
    })

    // 删除成员
    memberRecords.value = memberRecords.value.filter(record =>
      !memberIdsToDelete.includes(record.memberId))

    selectedRecords.value = []
  }

  updatePagination()
  showDeleteConfirm.value = false
  deleteTarget.value = {}
}

const cancelDelete = () => {
  showDeleteConfirm.value = false
  deleteTarget.value = {}
}

const handleSave = () => {
  // 更新时间
  currentRecord.value.updateTime = new Date().toLocaleString()

  if (modalType.value === 'add') {
    if (currentRecord.value.identity === '租户') {
      const newTenant = {
        tenementId: Date.now(),
        name: currentRecord.value.name,
        gender: parseInt(currentRecord.value.gender),
        phone: currentRecord.value.phone,
        phoneNumber: currentRecord.value.phone,
        idCard: currentRecord.value.idCard,
        remark: currentRecord.value.remark,
        createBy: '当前用户',
        updateBy: '当前用户',
        createTime: new Date().toLocaleString(),
        updateTime: new Date().toLocaleString(),
        identity: '租户'
      }
      tenantRecords.value.push(newTenant)
    } else {
      const newMember = {
        memberId: Date.now(),
        tenementId: currentRecord.value.tenantId,
        memberName: currentRecord.value.name,
        gender: parseInt(currentRecord.value.gender),
        memberPhone: currentRecord.value.phone,
        idCard: currentRecord.value.idCard,
        relationship: currentRecord.value.relationshipWithTenant,
        remark: currentRecord.value.remark,
        createBy: '当前用户',
        updateBy: '当前用户',
        createTime: new Date().toLocaleString(),
        updateTime: new Date().toLocaleString(),
        identity: '成员'
      }
      memberRecords.value.push(newMember)
    }
  } else if (modalType.value === 'edit') {
    if (recordType.value === 'tenant') {
      const index = tenantRecords.value.findIndex(record =>
        record.tenementId === currentRecord.value.id)
      if (index !== -1) {
        tenantRecords.value[index] = {
          ...tenantRecords.value[index],
          name: currentRecord.value.name,
          gender: parseInt(currentRecord.value.gender),
          phone: currentRecord.value.phone,
          phoneNumber: currentRecord.value.phone,
          idCard: currentRecord.value.idCard,
          remark: currentRecord.value.remark,
          updateBy: '当前用户',
          updateTime: new Date().toLocaleString()
        }
      }
    } else {
      const index = memberRecords.value.findIndex(record =>
        record.memberId === currentRecord.value.id)
      if (index !== -1) {
        memberRecords.value[index] = {
          ...memberRecords.value[index],
          memberName: currentRecord.value.name,
          gender: parseInt(currentRecord.value.gender),
          memberPhone: currentRecord.value.phone,
          idCard: currentRecord.value.idCard,
          relationship: currentRecord.value.relationshipWithTenant,
          remark: currentRecord.value.remark,
          updateBy: '当前用户',
          updateTime: new Date().toLocaleString()
        }
      }
    }
  }

  updatePagination()
  closeModal()
}

const closeModal = () => {
  showModal.value = false
  currentRecord.value = {}
  // 重置操作模式
  if (operationMode.value === 'add-member') {
    operationMode.value = ''
    showAddMemberButton.value = false
  }
}

const goToPage = (page) => {
  if (page >= 1 && page <= pagination.value.totalPages) {
    pagination.value.currentPage = page
    selectedRecords.value = []
  }
}

const goToPrevPage = () => {
  if (pagination.value.currentPage > 1) {
    pagination.value.currentPage--
    selectedRecords.value = []
  }
}

const goToNextPage = () => {
  if (pagination.value.currentPage < pagination.value.totalPages) {
    pagination.value.currentPage++
    selectedRecords.value = []
  }
}

const handleGotoPage = () => {
  const page = parseInt(gotoPage.value)
  if (page >= 1 && page <= pagination.value.totalPages) {
    pagination.value.currentPage = page
    gotoPage.value = ''
    selectedRecords.value = []
  }
}

// 获取户主的成员列表
const getMembersByTenantId = (tenantId) => {
  return memberRecords.value.filter(record => record.tenementId === tenantId)
}

// 根据ID获取户主姓名
const getTenantNameById = (tenantId) => {
  const tenant = tenantRecords.value.find(record => record.tenementId === tenantId)
  return tenant ? tenant.name : ''
}

// 生命周期
onMounted(() => {
  fetchRecords()
})
</script>

<style scoped>
/* 基础布局样式 */
.person-management {
  width: 100%;
  background-color: rgba(255, 255, 255, 1);
  padding: 30px 30px;
  box-sizing: border-box;
  overflow: hidden;
  border-radius: 0 15px 15px 15px;
}

/* 页面标题 */
.page-title {
  color: rgba(231, 59, 69, 1);
  font-size: 18px;
  font-family: PingFangSC-Medium;
  font-weight: 500;
  margin: 0 0 20px 0;
  line-height: 25px;
}

/* 搜索筛选区域 */
.search-filters {
  margin-bottom: 6px;
}

.search-item {
  display: block;
  margin-bottom: 5px;
}

.filter-row {
  display: flex;
  align-items: center;
  gap: 20px;
  flex-wrap: wrap;
  width: 1527px;
  height: 32px;
}

/* 统一的输入框和选择框样式 */
.input-field, .select-field {
  background-color: rgba(255, 255, 255, 1);
  border-radius: 4px;
  height: 32px;
  border: 1px solid rgba(216, 216, 216, 1);
  width: 180px;
  padding: 6px 10px;
  font-size: 14px;
  color: rgba(153, 153, 153, 1);
  box-sizing: border-box;
  line-height: 20px;
}

.input-field:focus, .select-field:focus {
  outline: none;
  border-color: rgba(231, 59, 69, 1);
  color: rgba(0, 0, 0, 1);
}

.input-field::placeholder {
  color: rgba(153, 153, 153, 1);
}

/* 统一的按钮样式 */
.btn-primary {
  background-color: rgba(231, 59, 69, 1);
  border-radius: 4px;
  width: 80px;
  height: 32px;
  border: none;
  color: rgba(255, 255, 255, 1);
  font-size: 14px;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 5px;
  cursor: pointer;
  margin-left: 20px;
}

.btn-secondary {
  background-color: rgba(255, 255, 255, 1);
  border-radius: 4px;
  width: 80px;
  height: 32px;
  border: 1px solid rgba(151, 151, 151, 1);
  color: rgba(135, 136, 138, 1);
  font-size: 14px;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 6px;
  cursor: pointer;
}

.btn-add {
  background-color: rgba(252, 235, 236, 1);
  border-radius: 19px;
  width: 80px;
  height: 32px;
  border: none;
  color: rgba(231, 59, 69, 1);
  font-size: 14px;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8px;
  cursor: pointer;
  transition: all 0.3s ease;
}

.btn-add:hover {
  background-color: rgba(248, 220, 222, 1);
}

.btn-export {
  background-color: rgba(255, 255, 255, 1);
  border-radius: 4px;
  width: 80px;
  height: 32px;
  border: 1px solid rgba(151, 151, 151, 1);
  color: rgba(135, 136, 138, 1);
  font-size: 14px;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8px;
  cursor: pointer;
  transition: all 0.3s ease;
}

.btn-export:hover {
  background-color: rgba(245, 245, 245, 1);
}

.btn-batch-delete {
  background-color: rgba(255, 77, 79, 1);
  border-radius: 19px;
  height: 32px;
  padding: 0 16px;
  border: none;
  color: rgba(255, 255, 255, 1);
  font-size: 14px;
  cursor: pointer;
  margin-left: 20px;
}

.btn-batch-delete:hover {
  background-color: rgba(235, 57, 59, 1);
}

.btn-icon {
  width: 13px;
  height: 13px;
}

/* 分割线 */
.divider {
  width: 1533px;
  height: 1px;
  background-color: rgba(237, 239, 244, 1);
  margin: 50px 0 0 0;
}

/* 操作按钮组样式 */
.operation-buttons {
  display: flex;
  align-items: center;
  justify-content: flex-end;
  gap: 10px;
  margin: 20px 0;
}

/* 表格样式 */
.table-container {
  background-color: rgba(255, 255, 255, 1);
  border-radius: 4px;
  border: 1px solid rgba(237, 239, 244, 1);
  width: 100%;
  height: 610px;
  overflow: hidden;
}

.data-table {
  width: 100%;
  border-collapse: collapse;
}

.table-header {
  background-color: rgba(249, 248, 252, 1);
  height: 60px;
  border-radius: 4px;
  border: 1px solid rgba(237, 239, 244, 1);
}

.table-header th {
  color: rgba(0, 0, 0, 1);
  font-size: 16px;
  font-weight: normal;
  text-align: left;
  padding: 13px 21px;
  line-height: 20px;
}

.table-row {
  background-color: rgba(255, 255, 255, 1);
  height: 55px;
  border: 1px solid rgba(237, 239, 244, 1);
}

.member-row {
  background-color: rgba(249, 248, 252, 1);
}

.table-row td {
  color: rgba(102, 102, 102, 1);
  font-size: 16px;
  font-weight: normal;
  padding: 10px 21px;
  line-height: 20px;
  white-space: nowrap;
}

/* 复选框样式 */
.checkbox {
  width: 16px;
  height: 16px;
  cursor: pointer;
}

/* 操作按钮样式 */
.action-buttons {
  display: flex;
  gap: 20px;
  align-items: center;
}

.action-btn {
  background: none;
  border: none;
  cursor: pointer;
  padding: 0;
  display: flex;
  align-items: center;
  justify-content: center;
}

.action-btn img {
  width: 13px;
  height: 13px;
}

/* 分页样式 */
.pagination {
  display: flex;
  align-items: center;
  justify-content: flex-end;
  gap: 10px;
  margin-top: 20px;
}

.pagination-info {
  color: rgba(102, 102, 102, 1);
  font-size: 14px;
  line-height: 20px;
}

.pagination-btn {
  background-color: rgba(255, 255, 255, 1);
  border: 1px solid rgba(216, 216, 216, 1);
  border-radius: 4px;
  padding: 6px 12px;
  font-size: 14px;
  color: rgba(102, 102, 102, 1);
  cursor: pointer;
  min-width: 32px;
  height: 32px;
  line-height: 20px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.pagination-btn:hover:not(:disabled) {
  background-color: rgba(249, 248, 252, 1);
}

.pagination-btn.active {
  background-color: rgba(231, 59, 69, 1);
  color: white;
  border-color: rgba(231, 59, 69, 1);
}

.pagination-btn:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}

.pagination-goto {
  color: rgba(102, 102, 102, 1);
  font-size: 14px;
  line-height: 20px;
  margin-left: 20px;
}

.goto-input {
  width: 50px;
  height: 32px;
  border: 1px solid rgba(216, 216, 216, 1);
  border-radius: 4px;
  padding: 6px;
  font-size: 14px;
  text-align: center;
  line-height: 20px;
}

/* 弹窗样式 */
.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
}

.modal-content {
  background-color: white;
  border-radius: 8px;
  width: 800px;
  max-height: 80vh;
  overflow-y: auto;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.15);
}

.add-type-modal {
  width: 400px;
}

.delete-confirm-modal {
  width: 400px;
  max-height: none;
  overflow-y: visible;
}

.modal-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px;
  border-bottom: 1px solid rgba(237, 239, 244, 1);
}

.modal-header h3 {
  margin: 0;
  font-size: 18px;
  color: rgba(231, 59, 69, 1);
  font-weight: 500;
}

.close-btn {
  background: none;
  border: none;
  font-size: 24px;
  cursor: pointer;
  color: rgba(102, 102, 102, 1);
  width: 30px;
  height: 30px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.close-btn:hover {
  color: rgba(231, 59, 69, 1);
}

.modal-body {
  padding: 20px;
}

.modal-body p {
  font-size: 14px;
  color: rgba(102, 102, 102, 1);
  line-height: 1.5;
  margin: 0;
}

.add-type-options {
  display: flex;
  flex-direction: column;
  gap: 20px;
  align-items: center;
  padding: 40px 0;
}

.add-type-btn {
  background-color: rgba(231, 59, 69, 1);
  border: none;
  border-radius: 4px;
  padding: 12px 30px;
  font-size: 16px;
  color: white;
  cursor: pointer;
  line-height: 20px;
  width: 200px;
}

.add-type-btn:hover {
  background-color: rgba(207, 53, 63, 1);
}

.form-grid {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 20px;
}

.form-item {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.form-item label {
  font-size: 14px;
  color: rgba(0, 0, 0, 1);
  font-weight: 500;
  line-height: 20px;
}

.form-input {
  height: 32px;
  border: 1px solid rgba(216, 216, 216, 1);
  border-radius: 4px;
  padding: 6px 10px;
  font-size: 14px;
  color: rgba(0, 0, 0, 1);
  line-height: 20px;
  box-sizing: border-box;
}

.form-input:focus {
  outline: none;
  border-color: rgba(231, 59, 69, 1);
}

.form-input:disabled {
  background-color: rgba(249, 248, 252, 1);
  color: rgba(153, 153, 153, 1);
  cursor: not-allowed;
}

.form-textarea {
  height: 60px;
  border: 1px solid rgba(216, 216, 216, 1);
  border-radius: 4px;
  padding: 6px 10px;
  font-size: 14px;
  color: rgba(0, 0, 0, 1);
  line-height: 20px;
  box-sizing: border-box;
  resize: vertical;
}

.form-textarea:focus {
  outline: none;
  border-color: rgba(231, 59, 69, 1);
}

.form-textarea:disabled {
  background-color: rgba(249, 248, 252, 1);
  color: rgba(153, 153, 153, 1);
  cursor: not-allowed;
}

/* 详情弹窗样式 */
.detail-grid {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 20px;
}

.detail-item {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.detail-item label {
  font-size: 14px;
  color: rgba(0, 0, 0, 1);
  font-weight: 500;
  line-height: 20px;
}

.detail-item span {
  font-size: 14px;
  color: rgba(102, 102, 102, 1);
  line-height: 20px;
}

/* 系统信息样式 */
.system-info {
  margin-top: 20px;
  padding-top: 20px;
  border-top: 1px solid rgba(237, 239, 244, 1);
}

.system-info h4 {
  margin: 0 0 15px 0;
  font-size: 16px;
  color: rgba(0, 0, 0, 1);
  font-weight: 500;
}

.modal-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
  padding: 20px;
  border-top: 1px solid rgba(237, 239, 244, 1);
}

.btn-cancel {
  background-color: rgba(255, 255, 255, 1);
  border: 1px solid rgba(216, 216, 216, 1);
  border-radius: 4px;
  padding: 8px 20px;
  font-size: 14px;
  color: rgba(102, 102, 102, 1);
  cursor: pointer;
  line-height: 20px;
}

.btn-save, .btn-export-confirm {
  background-color: rgba(231, 59, 69, 1);
  border: none;
  border-radius: 4px;
  padding: 8px 20px;
  font-size: 14px;
  color: white;
  cursor: pointer;
  line-height: 20px;
}

.btn-delete {
  background-color: rgba(255, 77, 79, 1);
  border: none;
  border-radius: 4px;
  padding: 8px 20px;
  font-size: 14px;
  color: white;
  cursor: pointer;
  line-height: 20px;
}

.btn-cancel:hover {
  background-color: rgba(249, 248, 252, 1);
}

.btn-save:hover, .btn-export-confirm:hover {
  background-color: rgba(207, 53, 63, 1);
}

.btn-delete:hover {
  background-color: rgba(235, 57, 59, 1);
}

/* 响应式调整 */
@media (max-width: 768px) {
  .contact-fields {
    grid-template-columns: 1fr;
  }
}
</style>
